#pragma once

#include <logicsystem.h>
#include <filetransffersystem.h>
#include <filetransffermgr.h>
#include <boost/asio.hpp>
#include <boost/uuid.hpp>
#include <boost/bind.hpp>
#include <msg_node.h>
#include <queue>


class AsyncServer;

class Session:public std::enable_shared_from_this<Session> {
	friend class AsyncServer;
public:
	Session(boost::asio::io_context& ioct, AsyncServer* server);
	
	void startRead();

	std::string getId() { return this->sessionId_; }

	void asyncReadHeader();
	
	void asyncReadBody();

	bool postSendNode(std::shared_ptr<SendNode> sendNode);

	/// <summary>
	/// 从sendQueue_取出sendNode并发送，线程不安全！！！
	/// </summary>
	void asyncWrite();


	/// <summary>
	/// 从socket_读取指定长度len的字节，并保存到buffer_中
	/// </summary>
	/// <param name="size">需要读取的字节</param>
	/// <param name="bytesHasRead">已经读取的字节</param>
	/// <param name="handler">读取完毕的回调函数</param>
	void asyncReadLen(size_t size,size_t bytesHasRead,std::function<void(size_t bytesHasRead,const boost::system::error_code& ec)> handler);

	void close();

private:
	void readHeaderHandler(size_t bytesRead, const boost::system::error_code& error);
	
	void readBodyHandler(size_t bytesRead, const boost::system::error_code& error);

	void writeHandler(std::shared_ptr<Session> self, const boost::system::error_code& ec, size_t bytesWrite);

private:
	boost::asio::ip::tcp::socket socket_;
	std::string sessionId_;
	AsyncServer* server_;
	std::shared_ptr<MsgNode> recvMsgHeader_;
	std::shared_ptr<RecvNode> recvMsgData_;
	std::mutex sendLock_;
	std::queue<std::shared_ptr<SendNode>> sendQueue_;
	char buffer_[MSG_MAX_DATA_LEN];
	bool bClose_;
};